package cache

import (
	"errors"
	"log"
	storage "ozonTest/internal/dal/cache"
	"ozonTest/internal/domain/posts/model"
	"sync"
	"time"
)

type postDAO struct {
	db *storage.Database
	mu sync.RWMutex
}

func NewPostsRepo(db *storage.Database) *postDAO {
	return &postDAO{db: db}
}

func (p *postDAO) CreatePost(post *model.Post) error {
	p.mu.Lock()
	defer p.mu.Unlock()

	post.ID = len(p.db.Posts) + 1
	post.CreatedAt = time.Now()
	p.db.Posts[post.ID] = post

	log.Printf("Post created: %+v", post)
	return nil
}

func (p *postDAO) GetPost(id int) (*model.Post, error) {
	p.mu.Lock()
	defer p.mu.Unlock()

	post, exists := p.db.Posts[id]
	if !exists {
		err := errors.New("post not found")
		log.Printf("Error getting post by ID %d: %v", id, err)
		return nil, err
	}

	log.Printf("Post retrieved: %+v", post)
	return post, nil
}

func (p *postDAO) GetAllPosts() ([]model.Post, error) {
	p.mu.Lock()
	defer p.mu.Unlock()

	posts := make([]model.Post, 0, len(p.db.Posts))
	for _, post := range p.db.Posts {
		posts = append(posts, *post)
	}

	log.Printf("All posts retrieved: %+v", posts)
	return posts, nil
}

func (p *postDAO) DeletePost(id int) error {
	p.mu.Lock()
	defer p.mu.Unlock()

	if _, exists := p.db.Posts[id]; !exists {
		err := errors.New("post not found")
		log.Printf("Error deleting post by ID %d: %v", id, err)
		return err
	}

	delete(p.db.Posts, id)
	log.Printf("Post deleted: ID %d", id)
	return nil
}

func (p *postDAO) ChangeCommentsAllowed(postID int, commentsAllowed bool) error {
	p.mu.Lock()
	defer p.mu.Unlock()

	post, exists := p.db.Posts[postID]
	if !exists {
		err := errors.New("post not found")
		log.Printf("Error changing comments allowed for post ID %d: %v", postID, err)
		return err
	}

	post.CommentsEnabled = commentsAllowed
	p.db.Posts[postID] = post

	log.Printf("Comments allowed changed for post ID %d: %v", postID, commentsAllowed)
	return nil
}
